package com.rfid.config;

import com.rfid.AppNotifyImpl.MRfidReaderNotifyImpl;
import com.rfid.reader.MRfidReader;
import com.rfid.reader.RfidReader;
import com.rfid.transport.TransportThreadManager;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Service;

@Service
public class RfidService implements ApplicationRunner {

    @Autowired
    private TransportThreadManager transportThreadManager;

    @Autowired
    private MRfidReader rfidReader;

    @Value("${rfid.reader.ip:192.168.10.7}")
    private String readerIp;

    @Value("${rfid.reader.port:12345}")
    private int readerPort;

    private volatile boolean isInitialized = false;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        // Spring Boot启动完成后执行初始化
        initializeAndStartRfid();
    }

    public void initializeAndStartRfid() {
        try {
            System.out.println("Initializing RFID reader...");

            // 初始化传输管理器
            TransportThreadManager.initilizeTransportManager();

            // 连接读写器
            int result = rfidReader.ConnectPhysicalInterface(
                    readerIp, readerPort, null, 0, RfidReader.CONNECT_TYPE_NET_TCP_CLIENT);

            if (result == 0) {
                System.out.println("Connected to RFID reader successfully");

                // 设置通知回调
                rfidReader.setAppNotify(new TagProcessNotifyImpl());

                // 添加到传输管理器
                TransportThreadManager.getInstance().AddRfidReader(rfidReader);

                // 启动读取
                rfidReader.Reset();
                isInitialized = true;
                System.out.println("RFID reader started reading tags");
            } else {
                System.err.println("Failed to connect to RFID reader, result code: " + result);
            }
        } catch (Exception e) {
            System.err.println("Error initializing RFID reader: " + e.getMessage());
            e.printStackTrace();
        }
    }

    // 自定义通知实现类
    private class TagProcessNotifyImpl extends MRfidReaderNotifyImpl {
        @Override
        public int NotifyRecvTags(byte[] message, int startIndex) {
            // 调用父类处理（打印标签信息）
            super.NotifyRecvTags(message, startIndex);

            // 提取并处理标签数据
            processReceivedTag(message, startIndex);
            return 0;
        }
    }

    private void processReceivedTag(byte[] message, int startIndex) {
        try {
            StringBuilder epcDataBuilder = new StringBuilder();
            int start_tlv_pos = startIndex + 8;
            int param_len = message[startIndex + 6] & 0xFF;
            param_len = param_len << 8;
            param_len = message[startIndex + 7] & 0xFF;

            int index = 0;
            while (index < param_len) {
                if ((message[start_tlv_pos] & 0xFF) == 0x50) { // TLV_ONE_TAG_DATA
                    int tempInterIndex = 0;
                    while (tempInterIndex < (message[start_tlv_pos + 1] & 0xFF)) {
                        int tempInter_tlv_pos = start_tlv_pos + 2 + tempInterIndex;
                        int tempInter_tlv = message[tempInter_tlv_pos] & 0xFF;
                        int tempInter_tlv_len = message[tempInter_tlv_pos + 1] & 0xFF;

                        if (tempInter_tlv == 0x01) { // TLV_EPC
                            for (int iIndex = 0; iIndex < tempInter_tlv_len; iIndex++) {
                                epcDataBuilder.append(String.format("%02X",
                                        message[tempInter_tlv_pos + 2 + iIndex]));
                            }
                            break;
                        }
                        tempInterIndex += tempInter_tlv_len + 2;
                    }
                    break;
                }
                index += (message[start_tlv_pos + 1] & 0xFF) + 2;
                start_tlv_pos += (message[start_tlv_pos + 1] & 0xFF) + 2;
            }

            String epcData = epcDataBuilder.toString();
            if (!epcData.isEmpty()) {
                onTagReceived(epcData);
            }
        } catch (Exception e) {
            System.err.println("Error processing received tag: " + e.getMessage());
        }
    }

    // 标签接收处理方法
    public void onTagReceived(String epcData) {
        System.out.println("Tag received and processed: " + epcData);
        // 在这里添加您的业务逻辑
    }
}
